package com.jy.project.service.imp;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jy.project.domain.*;
import com.jy.project.dto.*;
import com.jy.project.enums.ApplyTypeEnum;
import com.jy.project.enums.ApplyTypeMatericalEnum;
import com.jy.project.enums.QualityStatusEnum;
import com.jy.project.ex.BizException;
import com.jy.project.mapper.*;
import com.jy.project.service.ApplyService;
import com.jy.project.service.imp.defult.DefaultApplyBusinessImp;
import com.jy.project.util.*;
import com.jy.project.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service("applyRenewServiceImpl")
@Slf4j
public class ApplyRenewServiceImpl extends DefaultApplyBusinessImp implements ApplyService {

    @Autowired
    private ApplyMapper applyMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private ApplyRenewMapper applyRenewMapper;


    @Autowired
    private ApplyBorrowMapper applyBorrowMapper;

    @Autowired
    DataSourceTransactionManager dataSourceTransactionManager;

    @Autowired
    TransactionDefinition transactionDefinition;


    @Override
    public boolean insertApply(ApplyDTO dto) {
        dto.setApplyType(ApplyTypeEnum.RENEW.getCode());
        Set<Integer> set = new HashSet<>();
        set.add(dto.getApplyType());
        dto.setExt(JSONObject.toJSONString(set));
        TransactionStatus transactionStatus = dataSourceTransactionManager.getTransaction(transactionDefinition);
        try {
            boolean bl = this.insertApplyBusiness(dto);
            if (bl == false) {
                throw new BizException("申请借用失败");
            }
        }catch (Exception e){
            dataSourceTransactionManager.rollback(transactionStatus);
            throw  e;
        }
        dataSourceTransactionManager.commit(transactionStatus);
        return true;
    }

    @Override
    public List<ApplyQualitVO> listApplyQualityVO(ApplyQueryDTO dto) {

        return applyMapper.listApplyyQualityVO(dto);
    }

    @Override
    public List<ApplyDeptAdminVO> listDeptAdminApplyVO(ApplyDeptAdminQueryDTO dto) {
        return null;
    }

    @Override
    public boolean applyAdopt(ApplyAdoptDTO dto) {
        log.info("审批通过续借单");
        Example example =new Example(ApplyRenew.class);
        example.createCriteria().andEqualTo("applyNo",dto.getApplyNo());
        List<ApplyRenew> applyRenewList = applyRenewMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(applyRenewList)){
            throw  new BizException("数据不存在");
        }
        List<String> applyNos=new ArrayList<>();
        for (int i = 0; i < applyRenewList.size(); i++) {
            applyNos.add(applyRenewList.get(i).getMaterialNo());
        }
        String s = CommonStringUtils.toStr(applyNos);
        return materialMapper.updateStatusMaterialNos(s,1)>0;
    }

    @Override
    public boolean applyReject(ApplyAdoptDTO dto) {
        log.info("驳回审批续借单");
        return true;
    }

    @Override
    public ServiceResultUtils listMaterialDetailsVO(MaterialDetailsDTO dto) {
        return null;
    }

    @Override
    public List<ApplyUserVO> listUserApplyVO(ApplyUserQueryDTO dto) {
        return null;
    }


    @Override
    public void checkApplyNo(String applyNo) {


    }

    protected  Apply getApply(String applyNo){
        if (StringUtils.isEmpty(applyNo)){
            throw  new BizException("借用单号不能为空");
        }
        Example example =new Example(Apply.class);
        example.createCriteria().andEqualTo("isDelete",0)
                .andEqualTo("applyNo",applyNo);
        Apply apply = applyMapper.selectOneByExample(example);
        if (apply==null){
            throw new BizException("该借用单申请信息不存在");
        }
        return  apply;
    }
    @Override
    public MaterialVO checkMaterialNo(String materialNo) {
        return super.checkMaterialNo(materialNo);
    }

    @Override
    public boolean insertApplyBusiness(ApplyDTO dto) {
        if (dto==null){
            throw new BizException("Apply对象为空");
        }
        Apply apply = getApply(dto.getApplyNo());
        Apply ay = this.create();
        BeanUtils.copyProperties(apply,ay);
        ay.setId(null);
        ay.setApplyType(dto.getApplyType());
        ay.setName(ApplyTypeEnum.getValue(ay.getApplyType()));
        //制单人
        String token = dto.getToken();
        User u = JwtUtils.verifyToken(token);
        Long id = u.getId();
        User user = userMapper.selectByPrimaryKey(id);
        if (user==null){
            throw  new BizException("用户信息可能找不到");
        }
        MaterialDetailsDTO materialDetailsDTO = new MaterialDetailsDTO();
        materialDetailsDTO.setApplyNo(dto.getApplyNo());
        List<MaterialDetailsVO> materialDetailsVOS = applyBorrowMapper.listMaterialDetailsVO(materialDetailsDTO);
        if (CollectionUtils.isEmpty(materialDetailsVOS)){
            throw new BizException("找不到退库数据");
        }

        String[] split=new String[materialDetailsVOS.size()];
        for (int i = 0; i < materialDetailsVOS.size(); i++) {
            split[i]="'"+materialDetailsVOS.get(i).getMaterialNo()+"'";
        }
        checkMaterialNos(split);
        ay.setApplicantCompanyNo(user.getCompanyNo());
        ay.setApplicantCompanyName(user.getCompanyName());
        ay.setApplicantDeptNo(user.getDeptNo());
        ay.setApplicantDeptName(user.getDeptName());
        ay.setApplicantUserId(user.getId());
        ay.setApplicantUserNickName(user.getNickName());
        ay.setExt(dto.getExt());
        ay.setRemarks(dto.getRemarks());
        ay.setStatus(0);
        ApplyRenewDTO applyRenewDTO=(ApplyRenewDTO) dto;
        Integer renewDay = applyRenewDTO.getRenewDay();
        if (renewDay==null || renewDay==0){
            throw  new BizException("续借天数不能为空");
        }

        String s = CommonStringUtils.toStrNotQuotationMarks(split);
        List<ApplyBorrow> applyBorrows = applyBorrowMapper.listApplyBorrow(s);
        if (applyBorrows==null){
            throw  new BizException("找不到当前使用者的借用单");
        }
        log.info("applyBorrows size {} ",applyBorrows.size());

        if (applyBorrows.size()!=split.length){
            throw  new BizException("不存在借用单无法被续借");
        }
        List<ApplyRenew> applyRenewList=new ArrayList<>();
        for (int i = 0; i < applyBorrows.size(); i++) {
            ApplyBorrow applyBorrow = applyBorrows.get(i);
            ApplyRenew applyRenew=new ApplyRenew();
            BeanUtils.copyProperties(ay,applyRenew);
            applyRenew.setMaterialNo(applyBorrow.getMaterialNo());
            applyRenew.setMaterialName(applyBorrow.getMaterialName());
            applyRenew.setStatus(0);
            applyRenew.setImg(applyBorrow.getImg());
            Date returnDate = applyBorrow.getReturnDate();
            Calendar calendar = DateUtil.calendar(returnDate);
            calendar.add(Calendar.DATE, renewDay);// num为增加的天数，可以改变的
            applyRenew.setReturnDate(returnDate);
            applyRenew.setLatestReturnDate(calendar.getTime());
            applyRenew.setStatus(0);
            ApplyBorrow updateApplyBorrow=new ApplyBorrow();
            updateApplyBorrow.setId(applyBorrow.getId());
            updateApplyBorrow.setLatestReturnDate(calendar.getTime());
            int updateSize = applyBorrowMapper.updateByPrimaryKeySelective(updateApplyBorrow);
            if (updateSize<1){
                throw  new BizException(applyBorrow.getMaterialNo()+" 资产单借用失败");
            }
            applyRenewList.add(applyRenew);
        }
        applyRenewMapper.insertList(applyRenewList);
        applyMapper.insertSelective(ay);
        return true;
    }

    @Override
    public Apply create() {
        Apply apply = super.create();
        apply.setApplyNo(CodeUtils.generateApplyNo(ApplyTypeMatericalEnum.RENEW.getValue()));
        return apply;
    }

    private  List<MaterialVO> checkMaterialNos(String[] split){
        String s = CommonStringUtils.toStrNotQuotationMarks(split);
        List<MaterialVO> materialVOS = materialMapper.listMaterialVOByMaterialNos(s);

        for (int i = 0; i < materialVOS.size(); i++) {
            MaterialVO materialVO = materialVOS.get(i);
            Integer useStatus = materialVO.getUseStatus();
            String[] qualityStatus = materialVO.getQualityStatus();
            if (qualityStatus!=null ||qualityStatus.length>0){
                boolean bl=false;
                for (int j = 0; j < qualityStatus.length; j++) {
                    String qStatus = qualityStatus[j];
                    if (qStatus.equals(QualityStatusEnum.LOANABLE.getCode().toString())){
                        bl=true;
                    }
                }
                if (bl==false){
                    throw  new BizException("编号"+materialVO.getMaterialNo()+"资产质量状态设置不可领取");
                }
            }

        }
        return  materialVOS;
    }
}
